package com.syf.core;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

@Order(Ordered.LOWEST_PRECEDENCE)
@Component
public class SyApplicationRunner {
    private static CountDownLatch applicationHolLatch = new CountDownLatch(1);

    public static ConfigurableApplicationContext run(Class<?> primarySource, String[] args) {
        // springboot ioc
        SpringApplication springApplication = new SpringApplication(primarySource, SyApplicationRunner.class);
        // 去掉spring自带钩子
        springApplication.setRegisterShutdownHook(false);
        ConfigurableApplicationContext springContext = springApplication.run(args);

        // 注册自己的钩子
        final SyApplicationShutdownHook myHook = new SyApplicationShutdownHook(springContext);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                myHook.shutdownGracefully();
            }
        });

        continuousApplication();
        return springContext;
    }

    private static void continuousApplication() {
        new Thread(() -> {
            try {
                applicationHolLatch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException("程序被意外打断", e);
            }
        }).start();
    }
}
